package com.yiwei.jmx.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.jmx.R;
import com.yiwei.jmx.activity.AllRankActivity;
import com.yiwei.jmx.activity.LoginTotalActivity;
import com.yiwei.jmx.activity.MyQrCodeSecActivity;
import com.yiwei.jmx.activity.MyRewardActivity;
import com.yiwei.jmx.activity.WebViewActivity;
import com.yiwei.jmx.adapter.MainHomeOrderAdapter;
import com.yiwei.jmx.adapter.MainHomePrizeAdapter;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.PrizeRanksBean;
import com.yiwei.jmx.api.model.PrizeIndexModel;
import com.yiwei.jmx.api.model.PrizeRanksModel;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.util.GlideUtil;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.Spans;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.ConfirmPopWindow;
import com.yiwei.jmx.view.V19RelativeLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by xsooy-pc on 18-8-29.
 */

public class MainPrizeFragment extends BaseFragment {
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.txt_user)
    TextView txtUser;
    @BindView(R.id.btn_my_qrcode)
    LinearLayout btnMyQrcode;
    @BindView(R.id.layout_title)
    V19RelativeLayout layoutTitle;
    @BindView(R.id.view_bottom)
    View viewBottom;
    @BindView(R.id.img_total_bg)
    ImageView imgTotalBg;
    @BindView(R.id.btn_rule)
    SuperButton btnRule;
    @BindView(R.id.txt_prize_title)
    TextView txtPrizeTitle;
    @BindView(R.id.fl_prize_bg)
    FrameLayout flPrizeBg;
    @BindView(R.id.img_content_one)
    ImageView imgContentOne;
    @BindView(R.id.txt_invite_num)
    TextView txtInviteNum;
    @BindView(R.id.btn_invite_num)
    TextView btnInviteNum;
    @BindView(R.id.txt_money_num)
    TextView txtMoneyNum;
    @BindView(R.id.btn_money_num)
    TextView btnMoneyNum;
    @BindView(R.id.txt_thing_num)
    TextView txtThingNum;
    @BindView(R.id.btn_thing_num)
    TextView btnThingNum;
    @BindView(R.id.fl_my_reward_bg)
    FrameLayout flMyRewardBg;
    @BindView(R.id.img_level_two)
    ImageView imgLevelTwo;
    @BindView(R.id.txt_level_two)
    TextView txtLevelTwo;
    @BindView(R.id.img_level_one)
    ImageView imgLevelOne;
    @BindView(R.id.txt_level_one)
    TextView txtLevelOne;
    @BindView(R.id.img_level_three)
    ImageView imgLevelThree;
    @BindView(R.id.txt_level_three)
    TextView txtLevelThree;
    @BindView(R.id.layout_icon_one)
    LinearLayout layoutIconOne;
    @BindView(R.id.layout_money_title)
    LinearLayout layoutMoneyTitle;
    @BindView(R.id.list_two)
    RecyclerView listTwo;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.ll_money_bg)
    LinearLayout llMoneyBg;
    @BindView(R.id.img_level_two_sec)
    ImageView imgLevelTwoSec;
    @BindView(R.id.txt_level_two_sec)
    TextView txtLevelTwoSec;
    @BindView(R.id.img_level_one_sec)
    ImageView imgLevelOneSec;
    @BindView(R.id.txt_level_one_sec)
    TextView txtLevelOneSec;
    @BindView(R.id.img_level_three_sec)
    ImageView imgLevelThreeSec;
    @BindView(R.id.txt_level_three_sec)
    TextView txtLevelThreeSec;
    @BindView(R.id.layout_icon_two)
    LinearLayout layoutIconTwo;
    @BindView(R.id.layout_money_title_sec)
    LinearLayout layoutMoneyTitleSec;
    @BindView(R.id.list_three)
    RecyclerView listThree;
    @BindView(R.id.ll_rank_bg)
    LinearLayout llRankBg;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.img_icon_one)
    ImageView imgIconOne;
    @BindView(R.id.txt_user_one)
    TextView txtUserOne;
    @BindView(R.id.layout_float_one)
    LinearLayout layoutFloatOne;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    Unbinder unbinder;
    @BindView(R.id.img_update_prize)
    ImageView imgUpdatePrize;
    @BindView(R.id.layout_total_bg)
    RelativeLayout layoutTotalBg;
    @BindView(R.id.layout_has_data)
    LinearLayout layoutHasData;
    @BindView(R.id.btn_menu_one)
    TextView btnMenuOne;
    @BindView(R.id.btn_menu_two)
    TextView btnMenuTwo;
    private MainHomeOrderAdapter adapterReward;
    private MainHomePrizeAdapter adapterPrize;
    private ConfirmPopWindow confirmPopWindow;
    private ObjectAnimator animation;
    private List<PrizeIndexModel.DataBean.InviteListBean> invite_list;
    private int num;
    private ArrayList<PrizeIndexModel.DataBean.WeekListBean> totalWeekData;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_main_home_prize;
    }

    @Override
    protected void initView() {
        initAnimation();
        GlideUtil.loadImg(this, R.mipmap.img_prize_main_bg, layoutTotalBg);
        Glide.with(this).load(R.mipmap.img_prize_head).into(imgTotalBg);
        GlideUtil.loadImg(this, R.mipmap.img_prize_bg_one, flPrizeBg);
        GlideUtil.loadImg(this, R.mipmap.img_prize_bg_two, flMyRewardBg);
        GlideUtil.loadImg(this, R.mipmap.img_prize_bg_three, llMoneyBg);
        GlideUtil.loadImg(this, R.mipmap.img_prize_bg_four, llRankBg);

        adapterReward = new MainHomeOrderAdapter(getContext());
        listTwo.setAdapter(adapterReward);

        adapterPrize = new MainHomePrizeAdapter(getContext());
        listThree.setAdapter(adapterPrize);

        confirmPopWindow = new ConfirmPopWindow(getContext());
        confirmPopWindow.setOnChooseListener(new ConfirmPopWindow.OnChooseListener() {
            @Override
            public void onSuccess(String number) {
                getPrizeRank(number);
            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPrizeIndex();
            }
        });
        getPrizeIndex();


        UI.setTvHtml(txtPrizeTitle, R.string.prize_title);


    }


    public void getPrizeIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);
        Api.api_service.getPrizeIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setIndexData(result.data);
                });
    }

    public void getPrizeRank(String week) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);
        PrizeRanksBean bean = new PrizeRanksBean();
        bean.week_num = week;
        Api.api_service.getPrizeRank(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setUpdatePirze(result.data);
                });
    }


    private void setIndexData(PrizeIndexModel.DataBean data) {
//        我的邀请数据
        totalWeekData = data.week_list;
        PrizeIndexModel.DataBean.StatisticsBean invite_data = data.statistics;
        txtInviteNum.setText(invite_data.register);
        txtMoneyNum.setText(invite_data.total);
        txtThingNum.setText(invite_data.week_ranking);

//        选择时间
        confirmPopWindow.setData(data.week_list);

//        奖品图片
        if (data.ads != null && data.ads.size() != 0) {
            Glide.with(this).load(data.ads.get(0)).into(imgUpdatePrize);
        }

//                    邀请列表
        invite_list = data.invite_list;
        if (invite_list != null && invite_list.size() != 0) {
            if (animation.isRunning()) {
                animation.cancel();
            }
            animation.start();
        }

        //        奖金排行榜
        setUpdatePirze(data.reward_list);


        //                    ======================================================================
//                        奖品大神磅
        List<PrizeIndexModel.DataBean.PrizeListBean> prize_list = data.prize_list;
        if (prize_list != null && prize_list.size() != 0) {
//                      奖品大神磅  排版前三名
            if (prize_list.size() == 1) {
                imgLevelOneSec.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(prize_list.get(0).header).error(R.mipmap.img_invite_level_one).into(imgLevelOneSec);
                txtLevelOneSec.setText(getPrizeInfo(prize_list.get(0).real_name, prize_list.get(0).goods));
//                txtLevelOneSec.setText(prize_list.get(0).real_name + "\n" + prize_list.get(0).goods);
                imgLevelTwoSec.setVisibility(View.INVISIBLE);
                txtLevelTwoSec.setText("");
                imgLevelThreeSec.setVisibility(View.INVISIBLE);
                txtLevelThreeSec.setText("");
            } else if (prize_list.size() == 2) {
                imgLevelOneSec.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(prize_list.get(0).header).error(R.mipmap.img_invite_level_one).into(imgLevelOneSec);
//                txtLevelOneSec.setText(prize_list.get(0).real_name + "\n" + prize_list.get(0).goods);
                txtLevelOneSec.setText(getPrizeInfo(prize_list.get(0).real_name, prize_list.get(0).goods));
                imgLevelTwoSec.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(prize_list.get(1).header).error(R.mipmap.img_invite_level_two).into(imgLevelTwoSec);
//                txtLevelTwoSec.setText(prize_list.get(1).real_name + "\n" + prize_list.get(1).goods);
                txtLevelTwoSec.setText(getPrizeInfo(prize_list.get(1).real_name, prize_list.get(1).goods));
                imgLevelThreeSec.setVisibility(View.INVISIBLE);
                txtLevelThreeSec.setText("");
            } else {
                imgLevelOneSec.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(prize_list.get(0).header).error(R.mipmap.img_invite_level_one).into(imgLevelOneSec);
//                txtLevelOneSec.setText(prize_list.get(0).real_name + "\n" + prize_list.get(0).goods);
                txtLevelOneSec.setText(getPrizeInfo(prize_list.get(0).real_name, prize_list.get(0).goods));
                imgLevelTwoSec.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(prize_list.get(1).header).error(R.mipmap.img_invite_level_two).into(imgLevelTwoSec);
//                txtLevelTwoSec.setText(prize_list.get(1).real_name + "\n" + prize_list.get(1).goods);
                txtLevelTwoSec.setText(getPrizeInfo(prize_list.get(1).real_name, prize_list.get(1).goods));
                imgLevelThreeSec.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(prize_list.get(2).header).error(R.mipmap.img_invite_level_three).into(imgLevelThreeSec);
//                txtLevelThreeSec.setText(prize_list.get(2).real_name + "\n" + prize_list.get(2).goods);
                txtLevelThreeSec.setText(getPrizeInfo(prize_list.get(2).real_name, prize_list.get(2).goods));
            }
            adapterPrize.update(prize_list);
        } else {
            imgLevelOneSec.setVisibility(View.INVISIBLE);
            imgLevelTwoSec.setVisibility(View.INVISIBLE);
            imgLevelThreeSec.setVisibility(View.INVISIBLE);
            txtLevelOneSec.setText("");
            txtLevelTwoSec.setText("");
            txtLevelThreeSec.setText("");
            adapterPrize.update(prize_list);
        }
    }

    private Spanned getPrizeInfo(String one, String two) {
        return Spans.with(this).font(one, getResources().getDimensionPixelSize(R.dimen.x28), 0xffFFFFFF).
                font("\n" + two, getResources().getDimensionPixelSize(R.dimen.x28), 0xffFFF000).style(Typeface.BOLD).
                build();
    }

    private void setUpdatePirze(List<PrizeRanksModel.DataBean> reward_list) {
        //        奖金排行榜
//        List<PrizeRanksModel.DataBean> reward_list =data.reward_list;
        if (reward_list != null && reward_list.size() != 0) {
            layoutHasData.setVisibility(View.VISIBLE);
            layoutEmpty.setVisibility(View.GONE);
            //                      奖金大神磅  排版前三名
            if (reward_list.size() == 1) {
                imgLevelOne.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(reward_list.get(0).header).error(R.mipmap.img_invite_level_one).into(imgLevelOne);

//                txtLevelOne.setText(reward_list.get(0).real_name + "\n￥" + reward_list.get(0).total_reward);

                txtLevelOne.setText(getPrizeInfo(reward_list.get(0).real_name, "￥" + reward_list.get(0).total_reward));
                imgLevelTwo.setVisibility(View.INVISIBLE);
                txtLevelTwo.setText("");
                imgLevelThree.setVisibility(View.INVISIBLE);
                txtLevelThree.setText("");
                adapterReward.update(new ArrayList<>());
            } else if (reward_list.size() == 2) {
                imgLevelOne.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(reward_list.get(0).header).error(R.mipmap.img_invite_level_one).into(imgLevelOne);
                txtLevelOne.setText(getPrizeInfo(reward_list.get(0).real_name, "￥" + reward_list.get(0).total_reward));
                imgLevelTwo.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(reward_list.get(1).header).error(R.mipmap.img_invite_level_two).into(imgLevelTwo);
//                txtLevelTwo.setText(reward_list.get(1).real_name + "\n￥" + reward_list.get(1).total_reward);
                txtLevelTwo.setText(getPrizeInfo(reward_list.get(1).real_name, "￥" + reward_list.get(1).total_reward));
                imgLevelThree.setVisibility(View.INVISIBLE);
                txtLevelThree.setText("");
                adapterReward.update(new ArrayList<>());
            } else {
                imgLevelOne.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(reward_list.get(0).header).error(R.mipmap.img_invite_level_one).into(imgLevelOne);
//                txtLevelOne.setText(reward_list.get(0).real_name + "\n￥" + reward_list.get(0).total_reward);
                txtLevelOne.setText(getPrizeInfo(reward_list.get(0).real_name, "￥" + reward_list.get(0).total_reward));
                imgLevelTwo.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(reward_list.get(1).header).error(R.mipmap.img_invite_level_two).into(imgLevelTwo);
//                txtLevelTwo.setText(reward_list.get(1).real_name + "\n￥" + reward_list.get(1).total_reward);
                txtLevelTwo.setText(getPrizeInfo(reward_list.get(1).real_name, "￥" + reward_list.get(1).total_reward));
                imgLevelThree.setVisibility(View.VISIBLE);
//                            Glide.with(getContext()).load(reward_list.get(2).header).error(R.mipmap.img_invite_level_three).into(imgLevelThree);
//                txtLevelThree.setText(reward_list.get(2).real_name + "\n￥" + reward_list.get(2).total_reward);
                txtLevelThree.setText(getPrizeInfo(reward_list.get(2).real_name, "￥" + reward_list.get(2).total_reward));
                if (reward_list.size() > 3) {
                    reward_list.remove(0);
                    reward_list.remove(0);
                    reward_list.remove(0);
                    adapterReward.update(reward_list);
                } else {
                    adapterReward.update(new ArrayList<>());
                }
            }
        } else {
            layoutHasData.setVisibility(View.GONE);
            layoutEmpty.setVisibility(View.VISIBLE);
        }
    }

    private void initAnimation() {
        animation = ObjectAnimator.ofFloat(layoutFloatOne, "alpha", 0f, 0.5f, 1f, 1f, 0f);
        animation.setRepeatCount(-1);
        animation.setDuration(5000);
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                txtUserOne.setText(invite_list.get(0).mobile + invite_list.get(0).name + "\n" + invite_list.get(0).text);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                int poi = num++ % invite_list.size();
                txtUserOne.setText(invite_list.get(poi).mobile + invite_list.get(poi).name + "\n" + invite_list.get(poi).text);

            }
        });
    }
    @Override
    public void onPause() {
        super.onPause();
        if(refresh!=null){
            refresh.setRefreshing(false);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        if (UserInfoGlobal.isLogin()) {
            txtUser.setText(UserInfoGlobal.getMobile());
        } else {
            txtUser.setText("未登录");
        }

        if (invite_list != null && invite_list.size() != 0) {
            animation.start();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.txt_user, R.id.btn_my_qrcode, R.id.btn_rule, R.id.btn_invite_num, R.id.btn_money_num, R.id.btn_thing_num, R.id.btn_menu_one, R.id.btn_menu_two})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.txt_user:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(getContext(), LoginTotalActivity.class);
                    return;
                }
                break;
            case R.id.btn_my_qrcode:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(getContext(), LoginTotalActivity.class);
                    return;
                }
                Util.startActivity(getContext(), MyQrCodeSecActivity.class);
                break;
            case R.id.btn_rule:
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "活动规则");
                intent.putExtra("url", Const.WebSite.PRIZE_RULE);
                startActivity(intent);
                break;
            case R.id.btn_invite_num:
            case R.id.btn_money_num:
            case R.id.btn_thing_num:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(getContext(), LoginTotalActivity.class);
                    return;
                }
                Util.startActivity(getContext(), MyRewardActivity.class);
                break;
            case R.id.btn_menu_one:
                confirmPopWindow.showAtBottom(btnMenuOne);
                break;
            case R.id.btn_menu_two:
                if (totalWeekData != null) {
                    Intent intent1 = new Intent(getContext(), AllRankActivity.class);
                    intent1.putParcelableArrayListExtra("data", totalWeekData);
                    startActivity(intent1);
                    getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                }

                break;
        }
    }
}
